package PrjHttpClt

import (
	"bytes"
	"dgo/goutils/utils"
	"dgo/goutils/yhttp"
	"errors"
	"fmt"
	"gitee.com/ymofen/supervalue"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
)

var (
	softDevNotifyVxFnList []func(caption, msg, remark string) bool
)

func PostJSONForTestEx(url string, req string, beforeRequest func(req *http.Request)) *wrapper.SuperValue {
	resp, err := PostJsonEx0(url, req, beforeRequest)
	if resp != nil {
		fmt.Println(resp.AsJSONStringEx(false, true))
	}
	if err != nil {
		fmt.Println(err.Error())
	}
	return resp
}

func PostJSONForTest(url string, req string) *wrapper.SuperValue {
	resp, err := PostJsonEx(url, req)
	if resp != nil {
		fmt.Println(resp.AsJSONString(false))
	}
	if err != nil {
		fmt.Println(err.Error())
	}
	return resp
}

func GetUrl(url string) ([]byte, error) {
	resp, err := yhttp.DefaultHttpGet(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode == 404 || resp.StatusCode == 503 {
		return nil, errors.New(resp.Status)
	}

	body, err := ioutil.ReadAll(resp.Body)
	return body, err

}

func DoHttpForward(url string, w http.ResponseWriter, r *http.Request) error {

	req, err := http.NewRequest(r.Method, url, r.Body)
	if err != nil {
		return err
	}

	for k, v := range r.Header {
		req.Header.Set(k, v[0])
	}
	resp, err := yhttp.DefHttpClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	for k, v := range resp.Header {
		w.Header().Set(k, v[0])
	}
	{
		_, err := io.Copy(w, resp.Body)
		return err
	}
}

func GetUrlAsJSONCache(url string, cache bool) (*wrapper.SuperValue, error) {
	resp, err := yhttp.DefaultHttpGet(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode == 404 || resp.StatusCode == 503 {
		return nil, errors.New(resp.Status)
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	strBody := string(body)
	strBody = utils.DelNonChineseCharEx(strBody, ' ')

	json, err := wrapper.NewSVFromBufCache([]byte(strBody), cache)
	if err != nil {
		return nil, err
	}

	if json == nil {
		return nil, fmt.Errorf("非法的响应数据:%s", string(body))
	}
	if json.IntByName("code", 0) == -1 {
		return json, errors.New(json.StringByName("msg", ""))
	}
	return json, nil

}

func GetUrlAsJSON(url string) (*wrapper.SuperValue, error) {
	resp, err := yhttp.DefaultHttpGet(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode == 404 || resp.StatusCode == 503 {
		return nil, errors.New(resp.Status)
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	strBody := string(body)
	strBody = utils.DelNonChineseCharEx(strBody, ' ')

	json, err := wrapper.NewSVFromBuf([]byte(strBody))
	if err != nil {
		return nil, err
	}

	if json == nil {
		return nil, fmt.Errorf("非法的响应数据:%s", string(body))
	}
	if json.IntByName("code", 0) == -1 {
		return json, errors.New(json.StringByName("msg", ""))
	}
	return json, nil
}

func PostRawBuf(url string, bodyBuf []byte, bodytype string) ([]byte, error) {
	resp, err := yhttp.DefaultHttpPost(url, bodytype, bytes.NewReader(bodyBuf))
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		return nil, errors.New(resp.Status)
	}
	body, err := ioutil.ReadAll(resp.Body)
	return body, err
}

func PostJson(url string, jsonstr string) ([]byte, error) {
	resp, err := yhttp.DefaultHttpPost(url, "application/json", strings.NewReader(jsonstr))
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode == 404 || resp.StatusCode == 503 {
		return nil, errors.New(resp.Status)
	}

	body, err := ioutil.ReadAll(resp.Body)
	return body, err
}

func PostJsonEx0(url string, jsonstr string, beforeReq func(req *http.Request)) (*wrapper.SuperValue, error) {
	resp, err := yhttp.DefaultHttpPostEx(url, "application/json", strings.NewReader(jsonstr), beforeReq)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode == 404 || resp.StatusCode == 503 {
		return nil, errors.New(resp.Status)
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	if len(body) == 0 {
		return nil, fmt.Errorf("响应数据为空")
	}

	json, err := wrapper.NewSVFromBuf(body)
	if err != nil {
		return nil, fmt.Errorf("解析响应数据:%s, 出现异常:%s", string(body), err.Error())
	}

	if json == nil {
		return nil, fmt.Errorf("非法的响应数据:%s", string(body))
	}
	if json.IntByName("code", 0) == -1 {
		msg := json.StringByName("msg", "")
		if len(msg) == 0 {
			msg = fmt.Sprintf("提取不到错误信息:%s", json.String())
		}
		return json, errors.New(msg)
	}
	return json, nil
}

func PostJsonEx(url string, jsonstr string) (*wrapper.SuperValue, error) {
	resp, err := yhttp.DefaultHttpPost(url, "application/json", strings.NewReader(jsonstr))
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode == 404 || resp.StatusCode == 503 {
		return nil, errors.New(resp.Status)
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	if len(body) == 0 {
		return nil, fmt.Errorf("响应数据为空")
	}

	json, err := wrapper.NewSVFromBuf(body)
	if err != nil {
		return nil, fmt.Errorf("解析响应数据:%s, 出现异常:%s", string(body), err.Error())
	}

	if json == nil {
		return nil, fmt.Errorf("非法的响应数据:%s", string(body))
	}
	if json.IntByName("code", 0) == -1 {
		msg := json.StringByName("msg", "")
		if len(msg) == 0 {
			msg = fmt.Sprintf("提取不到错误信息:%s", json.String())
		}
		return json, errors.New(msg)
	}
	return json, nil
}

func ExtractJsonErr(json *wrapper.SuperValue, onErrFunc func(errcode int, msg string)) {
	if json == nil {
		return
	}

	if json.IntByName("code", 0) == -1 {
		if onErrFunc != nil {
			onErrFunc(json.IntByName("errcode", 0), json.StringByName("msg", ""))
		}
	}
}

func PostJsonEx2(url string, jsonstr string) (*wrapper.SuperValue, error) {
	resp, err := yhttp.DefaultHttpPost(url, "application/json", strings.NewReader(jsonstr))
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode == 404 || resp.StatusCode == 503 {
		return nil, errors.New(resp.Status)
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	json, err := wrapper.NewSVFromBufCache(body, true)
	if err != nil {
		return nil, err
	}

	if json == nil {
		return nil, fmt.Errorf("非法的响应数据:%s", string(body))
	}
	return json, nil
}

func PostNotifyVX(openid, tel, templateid, caption, msg, remark string) error {
	url := "http://139.199.181.47:8090/vxtemplmsg-softdev/addtask"
	json := wrapper.NewSVObject()
	json.SetKeyValue("fopenid", openid)
	json.SetKeyValue("ftel", tel)
	json.SetKeyValue("fcaption", "softdev-notify")
	json.SetKeyValue("ftemplateid", templateid)
	json.SetKeyValue("ffirst", caption)
	json.SetKeyValue("fkeyword1", msg)
	json.SetKeyValue("fkeyword2", utils.NowString())
	json.SetKeyValue("fremark", remark)
	json.SetKeyValue("fstate", 0)
	resp, err := PostJsonEx2(url, json.AsJSONStringEx(false, false))
	if err != nil {
		return err
	}

	if resp.IntByName("code", 0) == -1 {
		return fmt.Errorf(resp.StringByName("msg", ""))
	}
	return nil
}

func PostSoftDevNotifyVx(caption, msg, remark string) error {
	if len(softDevNotifyVxFnList) > 0 {
		for i := 0; i < len(softDevNotifyVxFnList); i++ {
			fn := softDevNotifyVxFnList[i]
			if !fn(caption, msg, remark) {
				break
			}
		}
		return nil
	}
	url := "http://139.199.181.47:8090/vxtemplmsg-softdev/addtask"
	json := wrapper.NewSVObject()
	json.SetKeyValue("fopenid", "o2224jsjUZmNeFTqcC1WwGAPWzao")
	json.SetKeyValue("ftel", "17098900736")
	json.SetKeyValue("fcaption", "softdev-notify")
	json.SetKeyValue("ftemplateid", "6ITf0lgQobZoVIkKz2IGdoEZ3gSNrd-eoMZ9eYJzJaw")
	json.SetKeyValue("ffirst", caption)
	json.SetKeyValue("fkeyword1", msg)
	json.SetKeyValue("fkeyword2", utils.NowString())
	json.SetKeyValue("fremark", remark)
	json.SetKeyValue("fstate", 0)
	resp, err := PostJsonEx2(url, json.AsJSONStringEx(false, false))
	if err != nil {
		return err
	}

	if resp.IntByName("code", 0) == -1 {
		return fmt.Errorf(resp.StringByName("msg", ""))
	}
	return nil
}
